"use strict";

const fs = require("fs");

module.exports = () => async (ctx, next) => {
  ctx.put = (targetfile, yuanfile) => {
    return new Promise((resolve, reject) => {
      // 读文件流
      const rs = fs.createReadStream(yuanfile);
      // 写文件流
      const ws = fs.createWriteStream(targetfile);
      // 管道
      rs.pipe(ws);

      // 写入成功触发的事件
      ws.on("finish", () => {
        console.log("写入成功");
        resolve({
          url: targetfile,
        });
      });

      // 写入失败触发的事件
      console.log("写入失败");
      ws.on("error", (error) => {
        reject(error);
      });
    });
  };
  await next();
};
